<template>
  <view>
    <!-- 加载动画 -->
    <orange-fullloading
      text="加载中"
      :loadshow="loadingStatus">
    </orange-fullloading>
    <!-- 默认选择默认收货地址 -->
    <view class="bg-white ml-2 mr-2 mt-2 rounded">
      <view class="ml-2 font-s-5 pt-2">收货地址:
        <!--<text class="ml-3 default-address text-main-color font-s-3"></text>-->
      </view>
      <view class="row-ac-sb  pt-2 pb-3" @tap="chooseAddress">
        <view class="row-ac">
          <view class="iconfont icon-dizhi1 rounded-50 row bg-primary ml-2 font-s-8"
                style="width: 80rpx;height: 80rpx; "></view>
          <view class="ml-2">
            <view>{{defaultAddress.contact_name}}
              <text class="ml-3">{{defaultAddress.contact_phone}}</text>
            </view>
            <view class="text-secondary font-s-3">
              {{defaultAddress.province}}{{defaultAddress.city}}{{defaultAddress.district}}{{defaultAddress.address}}
            </view>
          </view>
        </view>
        <view class="iconfont icon-xiangxia mr-2 text-secondary"></view>
      </view>
    </view>
    <view class="bg-white ml-2 mr-2 mt-1 rounded" v-for="(item,index) in orderGoodsList.item" :key="index">
      <view class="row-ac pt-2">
        <image :src="item.img" class="rounded ml-2" mode=""
               style="width: 120rpx;height: 120rpx;"></image>
        <view class="flex-1 mr-4 ml-2">
          <view class="in2line font-s-4">{{item.product_name}}</view>
          <view class="mt-2 font-s-3 text-light-grey">规格：{{item.skuArr}}</view>
        </view>
      </view>
      <view class="d-f justify-end pb-3 mr-2 mt-2">
        <view class="font-s-6 mr-5">
          <text class="font-s-3">共{{item.amount}}件</text>
          ￥{{item.total_price}}
        </view>
      </view>
    </view>
    <!-- 支付方式选择 -->
    <view class="w-100 bg-white fixed-bottom border-top d-f justify-end align-center" style="height: 120rpx;">
      <view class="mr-5 font-s-5 ">实付款:
        <text class="mr-3 font-s-7">￥{{orderGoodsList.total_price}}</text>
      </view>
      <!--点击支付直接跳往支付平台-->
      <view @tap="toPay" class="ml-5 mr-2 bg-color row font-s-4"
            style="width: 180rpx;height: 65rpx;border-radius: 33rpx;">立即支付
      </view>
    </view>
  </view>
</template>


<script>
import uniNumberBox from '@/components/uni/uni-number-box/uni-number-box.vue'
import { getUserReceivingAddressUrl, createOrderAddViewUrl, createOrderAddViewByCartUrl,createOrderAddViewBySeckillUrl } from '@/api/index'

export default {
  components: {
    uniNumberBox,
  },
  data () {
    return {
      paymenIndex: 0,
      defaultAddress: {},
      // 直接购买，保存传过来的参数
      buyNowGoodsInfo: {},
      // 订单列表信息
      orderGoodsList: {},
      // 从那个地方进入这个页面【buyNow】商品详情页   【buyCart】购物车页面
      pageType: '',
      // 购物车页面进来的保存购物车列表id
      cartListId: [],
      loadingStatus: true,
      // 秒杀的活动id
      activeId:''
    }
  },
  onLoad (options) {
    this.initData(options)
  },
  onShow () {
    this.getNewAddress()
  },
  methods: {
    async initData (options) {
      let goodSku = ''
      if (options.orderType === 'buyNow') {
        // 商品详情页直接进来
        this.buyNowGoodsInfo = JSON.parse(options.goodsAttribute)
        this.pageType = 'buyNow'
        await this.getOrderGoodsInfo('buyNow')
      } else if (options.orderType === 'buyCart') {
        let shopCartGoodsId = options.goodsList.split(',')
        this.cartListId = shopCartGoodsId
        this.pageType = 'buyCart'
        // 购物车页面进来
        await this.getOrderGoodsInfo('buyCart', shopCartGoodsId)

      }else if(options.orderType === 'seckill'){
        // 从秒杀的商品详情页进来的
        this.activeId = options.activeId
        this.buyNowGoodsInfo = JSON.parse(options.goodsAttribute)
        this.buyNowGoodsInfo.sku[0].activityId = options.activeId
        this.pageType = 'seckill'
        await this.getOrderGoodsInfo('seckill')
      }
      this.getUserDefaultAddress()
      // 异步延迟加载
      setTimeout(() => {
        this.loadingStatus = false
      }, 100)
    },

    // 获取用户默认地址
    async getUserDefaultAddress () {
      this.defaultAddress = await uni.getStorageSync('defaultAddress')
      console.log(this.defaultAddress)
      console.log(this.defaultAddress == '')
      if (JSON.stringify(this.defaultAddress) == '{}' || this.defaultAddress == '' || this.defaultAddress == undefined) {
        console.log(1)
        // 如果缓存里面没有默认地址，那么从接口获取默认地址
        await this.$R.get(getUserReceivingAddressUrl).then(res => {
          console.log(2)
          if (res.data.length == 1) {
            uni.setStorage({
              key: 'defaultAddress',
              data: res.data[0],
            })
            this.defaultAddress = res.data[0]
          } else if (res.data.length > 1) {
            // 把默认地址放在第一个
            let httpDefaultAddress = ''
            for (let i = 0; i < res.data.length; i++) {
              console.log(res.data)
              if (res.data[i].is_default === 1) {
                httpDefaultAddress = res.data.splice(i, 1)
                // 把默认地址放到缓存中，用于后面调用
                uni.setStorage({
                  key: 'defaultAddress',
                  data: httpDefaultAddress[0],
                })
                this.defaultAddress = httpDefaultAddress[0]
              } else {

              }
            }
          } else {
            // 没有地址，要先让用户添加地址
            uni.showToast({
              title: '收货地址为空，请先编辑收货地址',
              icon: 'none',
              duration: 3000
            })
          }
        })
      }
    },
    // 获取用户重新地址
    getNewAddress () {
      let newAddress = this.$store.state.onceChooseAddress
      // 如果store里面的newAddress为空，直接返回
      if (JSON.stringify(newAddress) === '{}') {
        return false
      } else {
        console.log(newAddress)
        // 把用户选择的地址赋值
        this.defaultAddress = newAddress
        // 清空用户临时选择的地址
        this.$store.commit('toOnceChooseAddressChange', {})
      }

    },
    // 获取订单信息
    getOrderGoodsInfo (inType, shopCartGoodsId) {
      if (inType === 'buyNow') {
        // 如果是商品详情页直接来的
        this.$R.post(createOrderAddViewUrl, this.buyNowGoodsInfo)
          .then(res => {
            this.orderGoodsList = res.data
            this.orderGoodsList.item.forEach(item => {
              item.skuArr = []
              for (let j in item.product_specs) {
                item.skuArr.push(item.product_specs[j])
              }
              item.skuArr = item.skuArr.join('，')
            })
          })
      }
      else if (inType === 'buyCart') {
        this.$R.post(createOrderAddViewByCartUrl, { cartId: shopCartGoodsId })
          .then(res => {
            this.orderGoodsList = res.data
            this.orderGoodsList.item.forEach(item => {
              for (let j in item.product_specs) {
                item.skuArr = []
                item.skuArr.push(item.product_specs[j])
                item.skuArr = item.skuArr.join('，')
              }
            })
          })
      }
      else if(inType === 'seckill'){
        console.log(this.buyNowGoodsInfo)
        this.$R.post(createOrderAddViewBySeckillUrl, this.buyNowGoodsInfo)
          .then(res => {
            this.orderGoodsList = res.data
            this.orderGoodsList.item.forEach(item => {
              item.skuArr = []
              for (let j in item.product_specs) {
                item.skuArr.push(item.product_specs[j])
              }
              item.skuArr = item.skuArr.join('，')
            })
          })
      }
    },
    // 跳转到选择支付页面
    toPay () {
      console.log(this.pageType)
      if (this.pageType === 'buyNow') {
        // 从商品详情页进入购买
        let httpObj = {
          addressId: this.defaultAddress.id,
          sku: this.buyNowGoodsInfo.sku
        }
        // 保存订单参数到vuex中
        this.$store.commit('toPayHttpObjChange', httpObj)
        uni.navigateTo({
          url: '/pages/order/pay/pay?payType=buyNow'
        })
      } else if (this.pageType === 'buyCart') {
        let url = ''
        // 从购物车页面进入购买
        uni.navigateTo({
          url: `/pages/order/pay/pay?payType=buyCart&addressId=${this.defaultAddress.id}&cartId=${this.cartListId}`
        })
      }else if(this.pageType === 'seckill') {
        // 从商品详情页进入购买
        let httpObj = {
          addressId: this.defaultAddress.id,
          sku: this.buyNowGoodsInfo.sku
        }
        // 保存订单参数到vuex中
        this.$store.commit('toPayHttpObjChange', httpObj)
        uni.navigateTo({
          url: '/pages/order/pay/pay?payType=seckill'
        })
      }

    },
    chooseAddress () {
      uni.navigateTo({
        url: '/pages/user/configure/address?type=chooseAddress'
      })
    }
  }
}
</script>

<style lang="scss">
  page {
    background-color: $uni-bg-color-grey;
  }

  .default-address {
    padding: 2rpx 4rpx;
    border: 1rpx solid;
    border-radius: 4rpx;
  }

  .icon-gouxuan {
    color: $uni-text-white-color;
  }

  .active .icon-gouxuan {
    color: $main-color !important;
  }
</style>
